package com.stackoverflow;

import java.util.List;
import net.sf.stackwrap4j.query.UserQuery;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class UserList extends ListActivity implements OnClickListener {
	List<ListItem> listItems;
	Boolean isGoingToProfilePage;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.stringlist);
	    
	    String userName = getIntent().getStringExtra("userName");
	    isGoingToProfilePage = getIntent().getBooleanExtra("profilePage", false);
	    
	    UserQuery query = new UserQuery();
	    query.setFilter(userName);
	    listItems = Retriever.getInstance().getUsersByName(query);
	    
	    String[] displayArray = new String[listItems.size()];
	    int i = 0;
	    for (ListItem l: listItems)
	    {
	    	displayArray[i++] = (l.getOwner()+", "+l.getScore()+" reputation points");
	    }
	    
	    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, displayArray);
		setListAdapter(adapter);
		
		ListView mainListView = getListView();
        mainListView.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView adapterView, View view, int position, long id) {
            	// Get the question ID and pass it to the answer list activity
            	Intent i;
            	if (isGoingToProfilePage)
            		i = new Intent(UserList.this, ProfileDisplay.class);
            	else
            		i = new Intent(UserList.this, QuestionList.class);
            	ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();
            	String userName = adapter.getItem(position);
            	
            	for (ListItem l: listItems)
            	{
            		if (l.getOwner().equals(userName.substring(0, userName.indexOf(","))))
            			userName = userName + ";ID="+l.getId();
            	}
            	i.putExtra("tagName", "{user}"+userName);
            	startActivity(i);
            }
        });
	}
	
	public void onClick(View v) {
		
	}
}
